import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:ride_rex/article/detail/article_detail_page.dart';
import 'package:ride_rex/main/discover/discover_bean.dart';
import 'package:ride_rex/person_detail/person_detail_logic.dart';
import 'package:ride_rex/standard/app_colors.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../article/post/article_post_bean.dart';
import '../generated/assets.dart';
import '../main/mine/article/mine_article_page.dart';
import '../route.dart';

class PersonDetailPage extends GetView<PersonDetailLogic> {
  PersonDetailPage(this.bean, {super.key});

  final FeedUserBean bean;

  final String _tag = DateTime.now().toString();

  @override
  String? get tag => _tag;

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      scaffoldBackgroundColor: Colors.white,
      child: GetBuilder<PersonDetailLogic>(
        init: PersonDetailLogic(bean),
        tag: _tag,
        builder: (logic) {
          return Stack(
            children: [
              ExtendedNestedScrollView(
                controller: logic.scrollController,
                headerSliverBuilder: (BuildContext c, bool f) {
                  return <Widget>[SliverToBoxAdapter(child: _Header(bean))];
                },
                pinnedHeaderSliverHeightBuilder: () => ScreenUtil().statusBarHeight + 44,
                onlyOneScrollInBody: true,
                body: Column(
                  children: [
                    _buildTabs().padding(bottom: 16.w, top: 16.w),
                    Expanded(
                      child: TabBarView(
                        controller: logic.tabController,
                        children: <Widget>[
                          _TabPost(bean),
                          _TabMedal(bean),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              _buildAppBar(),
            ],
          );
        },
      ),
    );
  }

  Widget _buildTabs() {
    return Container(
      decoration: CommonDecoration.getShapeDecoration(
        bg: '#F4F4F4'.toColor,
        radius: 8.w,
        shadows: [
          BoxShadow(
            color: '#000000'.toColor.withOpacity(0.08),
            offset: const Offset(0, 2),
            blurRadius: 8,
          ),
        ],
      ),
      padding: EdgeInsets.all(3.w),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: List.generate(controller.titles.length, (index) {
          bool select = index == controller.selectIndex;
          return ButtonWidget.iconText(
            IconWidget.image(
              controller.icons[index],
              size: 20.w,
              color: select ? AppColors.primary : '#CCCCCC'.toColor,
            ),
            controller.titles[index],
            fontSize: 18,
            textColor: select ? AppColors.primary : '#CCCCCC'.toColor,
            fontWeight: select ? FontWeight.bold : FontWeight.normal,
            spacing: 8.w,
            onTap: () => controller.changeIndex(index),
            hasInkWell: false,
            width: 143.w,
            height: 44.w,
            alignment: Alignment.center,
            borderRadius: 8.w,
            backgroundColor: select ? Colors.white : Colors.transparent,
          );
        }).toList(),
      ),
    );
  }

  Widget _buildAppBar() {
    return ValueListenableBuilder(
      valueListenable: controller.appBarOpacityNotifier,
      builder: (BuildContext context, double value, Widget? child) {
        return Container(
          height: 44 + ScreenUtil().statusBarHeight,
          color: Colors.white.withOpacity(value),
          child: Column(
            children: [
              SizedBox(height: ScreenUtil().statusBarHeight),
              Row(
                children: [
                  const ButtonWidget.icon(
                    IconWidget.image(Assets.pngAppbarBackWhite, color: Colors.black, width: 20, height: 17),
                    padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                    onTap: CommonRoute.close,
                    hasInkWell: false,
                  ),
                  const Spacer(),
                  ButtonWidget.icon(
                    const IconWidget.image(Assets.pngDiscoverMore, size: 28),
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
                    onTap: () => CommonLogic.onTapMore(bean.userId ?? '', showFollow: bean.isFriend == false),
                    hasInkWell: false,
                  ),
                ],
              ).expanded(),
            ],
          ),
        );
      },
    );
  }
}

class _Header extends StatelessWidget {
  const _Header(this.bean);

  final FeedUserBean bean;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 170.w + ScreenUtil().statusBarHeight + 44,
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage(Assets.pngPersonDetailBg),
          fit: BoxFit.cover,
        ),
      ),
      child: Column(
        children: [
          Stack(
            alignment: Alignment.bottomRight,
            children: [
              _buildAvatar(),
              if (bean.isFriend == false) _buildAddFriend().positioned(right: 10.w),
            ],
          ).paddingTop(ScreenUtil().statusBarHeight + 44 + 32.w),
          _buildName().paddingTop(16.w),
        ],
      ),
    );
  }

  Widget _buildAddFriend() {
    return ButtonWidget(
      onTap: () async {
        Loading.show();
        await CommonLogic.follow(bean.userId ?? '');
        Loading.toast('Follow success', closeLoading: true);
      },
      hasInkWell: false,
      child: IconWidget.image(Assets.pngDiscoverAdd, size: 16.w),
    );
  }

  Widget _buildAvatar() {
    return ImageWidget.url(
      bean.avatar ?? '',
      borderWidth: 2.w,
      borderColor: Colors.white,
      width: 88.w,
      height: 88.w,
      radius: 88.w,
    );
  }

  Widget _buildName() => TextWidget.oneLine(
        text: bean.nickname ?? '',
        fontSize: 18,
        color: '#404040'.toColor,
        fontWeight: FontWeight.bold,
      );
}

class _TabPost extends StatelessWidget {
  const _TabPost(this.bean, {super.key});

  final FeedUserBean bean;

  @override
  Widget build(BuildContext context) {
    var works = bean.works ?? [];
    return GridView.builder(
      key: const PageStorageKey('Post'),
      padding: EdgeInsets.only(top: 16.w, left: 20.w, right: 20.w),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 15.w,
        crossAxisSpacing: 10.w,
        childAspectRatio: 0.7,
      ),
      itemBuilder: (context, index) {
        FeedUserWorkBean workBean = bean.works![index];
        PostArticleBean item = PostArticleBean(
          nickName: bean.nickname,
          avatar: bean.avatar,
          recordId: workBean.workId,
          userId: bean.userId,
          title: workBean.title,
          cover: ['assets/ride_rex_images/${workBean.cover}'],
        );
        return MineAticalItem(
          item,
          onTap: () {
            CommonRoute.open(ArticleDetailPage(bean, workBean));
          },
        );
      },
      itemCount: works.length,
    );
  }
}

class _TabMedal extends StatelessWidget {
  const _TabMedal(this.bean);

  final FeedUserBean bean;

  @override
  Widget build(BuildContext context) {
    var list = bean.landmarks ?? [];
    return GridView.builder(
      key: const PageStorageKey('Medal'),
      padding: EdgeInsets.only(top: 16.w),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        childAspectRatio: 1.1,
      ),
      itemBuilder: (context, index) {
        return Column(
          children: [
            IconWidget.image('assets/png/${list[index].medalIcon}.png', width: 104.w, height: 104.w),
            CommonTextUtils.getText(list[index].landmark ?? '', fontWeight: FontWeight.bold).paddingTop(12.w),
          ],
        );
      },
      itemCount: list.length,
    );
  }
}
